<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use App\Models\DataExcel;
use App\Models\Message;

class SendMultiMails extends Mailable
{
    use Queueable, SerializesModels;

    public $senderName, $sendermail, $recievermail, $content, $subject, $message, $file, $clickUrl, $openUrl;

    public function __construct($senderName, $sendermail, $recievermail, $content, $subject, $file = null, $message = null, $clickUrl = null, $openUrl = null)
    {
        $this->senderName = $senderName;
        $this->sendermail = $sendermail;
        $this->recievermail = $recievermail;
        $this->content = $content;
        $this->subject = $subject;
        $this->message = $message; 
        $this->file = $file;
        $this->clickUrl = $clickUrl;
        $this->openUrl = $openUrl;
    }

    public function build()
    {
        $email = $this->from($this->sendermail, $this->senderName)
            ->to($this->recievermail)
            ->subject($this->subject)
            ->view('emails.multimail')
            ->with([
                'sender' => $this->senderName,
                'reciever' => $this->recievermail,
                'subject' => $this->subject,
                'content' => $this->content,
                'clickUrl' => $this->clickUrl,
                'openUrl' => $this->openUrl,
            ]);


        if (!empty($this->file)) {
            $filePath = storage_path('app/public/' . $this->file);
            if (file_exists($filePath)) {
                $email->attach($filePath);
            } else {
                Log::error("Attachment file not found: " . $filePath);
            }
        }

        return $email;
    }

    // ✅ بعد الإرسال الناجح
    public function afterSend()
    {
        if (!$this->message) return;

        try {
            DataExcel::where('email', $this->recievermail)
                ->where('message_id', $this->message->id)
                ->update(['status' => 'sent']);

            $this->checkCompletion();
        } catch (\Exception $e) {
            Log::error("Failed to update status after sending: " . $e->getMessage());
        }
    }

    public function failed(\Exception $e)
    {
        if (!$this->message) return;

        try {
            DataExcel::where('email', $this->recievermail)
                ->where('message_id', $this->message->id)
                ->update(['status' => 'failed']);

            $this->checkCompletion();
            Log::error("Email failed to {$this->recievermail}: " . $e->getMessage());
        } catch (\Exception $ex) {
            Log::error("Failed to update status on failure: " . $ex->getMessage());
        }
    }

    private function checkCompletion()
    {
        $total = $this->message->dataExcels()->count();
        $sent = $this->message->dataExcels()->where('status', 'sent')->count();
        $failed = $this->message->dataExcels()->where('status', 'failed')->count();

        if (($sent + $failed) >= $total && $total > 0) {
            $status = ($failed === 0) ? 'completed' : 'failed';
            $this->message->update(['status' => $status, 'send_at' => now()]);
            Log::info("Message {$this->message->id} marked as {$status}");
        }
    }
}








